#include "glare.gles2.PixelShader.h"
#include "glare.gles2.Driver.h"
#include "glare.gles2.ShaderFactory.h"

namespace Glare {

	GLES2PixelShader::GLES2PixelShader(GLES2Driver* driver) 
		: _driver(driver)
		, _shader_id(0)
	{

	}

	GLES2PixelShader::~GLES2PixelShader()
	{
		Unload();
	}

	bool GLES2PixelShader::Compile(const string& shader_code, string* errors, const string& profile, const string& entry_point)
	{
		*errors = "";
		Unload();

		_shader_id = glCreateShader(GL_FRAGMENT_SHADER);
		EGL_CHECK_ERROR;

		uint len = shader_code.length();
		char* code = new char[len + 1];
		code[len] = '\0';

		strcpy(code, shader_code.c_str());
		glShaderSource(_shader_id, 1, (const char**)&code, NULL);

		delete[] code;

		glCompileShader(_shader_id);

		GLint shader_compiled;
		glGetShaderiv(_shader_id, GL_COMPILE_STATUS, &shader_compiled);

		if (!shader_compiled)
		{
			*errors = GLES2ShaderFactory::GetShaderError(_shader_id);
			return false;
		}

		return true;
	}

	void GLES2PixelShader::Unload()
	{
		glDeleteShader(_shader_id);
	}

	Driver* GLES2PixelShader::GetDriver() const
	{
		return _driver;
	}

	const GLuint& GLES2PixelShader::GetGLES2ShaderId() const
	{
		return _shader_id;
	}
}
